package cn.vic.db;

import cn.vic.config.TypeMapping;
import cn.vic.db.model.Column;
import cn.vic.db.model.Table;
import cn.vic.util.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MySqlDatabase extends DefaultDatabase {

    private static final String TABLE_COMMENTS_SQL = "show table status where NAME=?";

    public MySqlDatabase(Connection connection, TypeMapping typeMapping) {
        super(connection, typeMapping);
    }

    @Override
    public Table getTable(String catalog, String schema, String tableName) throws SQLException {
        Table table = super.getTable(catalog, schema, tableName);
        if (table != null) {
            this.getSysTable(table, catalog, schema, tableName);
            super.introspectTableComments(table, TABLE_COMMENTS_SQL, "COMMENT");
        }
        return table;
    }

    /**
     * 获取字段 类型 bigint(20)
     *
     * @param catalog
     * @param schema
     * @param tableName
     * @return
     */
    private void getSysTable(Table table, String catalog, String schema, String tableName) {
        ResultSet resultSet = null;
        try {
            StringBuffer sql = new StringBuffer("select COLUMN_NAME,COLUMN_DEFAULT,IS_NULLABLE,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,NUMERIC_PRECISION,COLUMN_TYPE,COLUMN_KEY,EXTRA,COLUMN_COMMENT ");
            sql.append(" from information_schema.COLUMNS").append(" where");
            sql.append(" TABLE_SCHEMA = ? and TABLE_NAME = ?");
            Connection connection = getConnection();
            String sqlCatalog;
            if (StringUtils.isNotBlank(catalog)) {
                sqlCatalog = catalog;
            } else if (StringUtils.isNotBlank(schema)) {
                sqlCatalog = schema;
            } else {
                sqlCatalog = connection.getCatalog();
            }
            PreparedStatement pstmt = connection.prepareStatement(sql.toString());
            pstmt.setObject(1, sqlCatalog);
            pstmt.setObject(2, tableName);
            resultSet = pstmt.executeQuery();

            while (resultSet.next()) {
                String columnName = resultSet.getString("COLUMN_NAME");
                String columnType = resultSet.getString("COLUMN_TYPE");
                Column column = table.getColumn(columnName);
                if (column != null) {
                    column.setColumnType(columnType);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(resultSet);
        }
    }

}
